const {promisify} = require('util')
const jwt = require('jsonwebtoken')
const sign = promisify(jwt.sign)
const verify = promisify(jwt.verify)

//生成token
module.exports.createToken = async (user)=>{
   
    const token = await sign(user,"dhjyyds",{
        expiresIn:'3d'
    })
    return token
}
//校验token
module.exports.verifyToken = (required=true)=>{
    return async (req,res,next)=>{
        let token = req.headers.authorization
        token = token?token.split('Bearea ')[1] : null
        if(token) {
            try {
                const user = await verify(token,"dhjyyds")
                req.user = user
                next()
            } catch (error) {
                res.status(401).json({
                    code:401,
                    message:'token验证失败或者已过期,请重新登录',
                })
            }
        }else if (required) {
            res.status(401).json({
                code:401,
                    message:'请先登录',
            })
        }else {
            next()
        }
    }
}

// const test = async ()=>{
//     console.log( await this.createToken({name:'张三',id:123}));
// }

// test()